package cn.ac.siom.query.action;

import cn.ac.siom.query.service.IaccessService;
import cn.ac.siom.query.service.Ikjjggs_newsService;
import cn.ac.siom.query.util.action.DefaultAction;
import cn.ac.siom.query.vo.Accessinfo;
import cn.ac.siom.query.vo.kjjggs_news;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.*;

@SuppressWarnings("unchecked")
@Controller
@RequestMapping(value = "/home/*")
public class kjjggs_newsAction extends DefaultAction {
    @Autowired
    private Config config; //引用统一的参数配置类
    @Resource
    private Ikjjggs_newsService kjjggs_newsService;
    @Resource
    private IaccessService iaccessService;

    /**
     * 激光通讯首页-科学普及信息
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "findByParams")
    public @ResponseBody Map findByParams(HttpServletRequest request) {
        Map params=getParameterMap(request);
        try {
            insertAccessinfo(request,"首页科学普及");
            return this.kjjggs_newsService.findByParams(params);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping(value = "kjjggs_news_list")
    public void list(HttpServletRequest request, HttpServletResponse response) {
        try {
            insertAccessinfo(request,"首页最新新闻");
            super.printObjectToList(response, "allkjjggs_news", this.kjjggs_newsService.list());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @ResponseBody
    @RequestMapping(value = "findNO_kjjggs_news", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public List<kjjggs_news> findNO(Integer i_id, HttpServletRequest request, Accessinfo accessinfo) throws SQLException {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        String url = request.getHeader("Referer");
        if (url == null) {
            accessinfo.setUrl("list.html?allList=8");
        } else {
            accessinfo.setUrl(url);
        }
        accessinfo.setIp(ip);
        accessinfo.setName("最新新闻详情页");
        this.iaccessService.insertOne(accessinfo);
        List<kjjggs_news> kjjggs_newss = this.kjjggs_newsService.list_NO(i_id);
        return kjjggs_newss;
    }

    @ResponseBody
    @RequestMapping(value = "findPage_kjjggs_news", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public Map<String, Object> findPage(Integer rownum, Integer page_id, HttpServletRequest request, Accessinfo accessinfo) throws SQLException {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        String url = request.getHeader("Referer");
        if (url == null) {
            accessinfo.setUrl("/");
        } else {
            if (url.contains("?")){
                accessinfo.setUrl(url);
                accessinfo.setName("最新新闻分页");
                accessinfo.setIp(ip);
                this.iaccessService.insertOne(accessinfo);
            }
        }
        List<kjjggs_news> kjjggs_newss = this.kjjggs_newsService.list_page(rownum, page_id);
        Integer cont = this.kjjggs_newsService.list_count();
        Map<String, Object> map = new HashMap<>();
        map.put("kjjggs_newss", kjjggs_newss);
        map.put("cont", cont);
        map.put("page_id", page_id);
        return map;
    }


    @ResponseBody
    @RequestMapping(value = "findPhoto_kjjggs_news", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public String findPhoto(HttpServletRequest request, Integer i_id) throws SQLException, IOException {
        insertAccessinfo(request,"加载图片");
        String kjjggs_news_photo = this.kjjggs_newsService.list_Photo(i_id);
        return kjjggs_news_photo;
    }


    @RequestMapping(value = "kggjjs_news_insert")
    public void insert(kjjggs_news vo, HttpServletRequest request, HttpServletResponse response) {
        //保存数据库的路径
        String sqlPath = null;
        //定义文件保存的本地路径(相对路径)
        String Image_Path = config.Image_path_images;
        //定义文件保存的本地路径(绝对路径路径)
        String localPath = request.getSession().getServletContext().getRealPath(Image_Path);
        //定义 文件名
        String filename = null;
        if (!vo.getFile().isEmpty()) {
            //生成uuid作为文件名称
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            //获得文件类型（可以判断如果不是图片，禁止上传）
            String contentType = vo.getFile().getContentType();
            //获得文件后缀名
            String suffixName = contentType.substring(contentType.indexOf("/") + 1);
            //得到 文件名
            filename = uuid + "." + suffixName;
            //文件保存路径
            try {
                vo.getFile().transferTo(new File(localPath + File.separator + filename));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //把图片的相对路径保存至数据库
        sqlPath = filename;
        vo.setImage(sqlPath);
        vo.setLeibie("lasercomm"); //类别是激光通讯
        try {
            if (this.kjjggs_newsService.insert(vo)) {
                super.print(response, "success");
            } else {
                super.print(response, "failure");
            }
        } catch (Exception e) {
            e.printStackTrace();
            super.print(response, "failure");
        }
    }

    @RequestMapping(value = "kggjjs_news_delete")
    public void delete(HttpServletRequest request, HttpServletResponse response) {
        try {
            String result[] = request.getParameter("ids").split("\\|");
            List<String> all = new ArrayList<>();
            for (int x = 0; x < result.length; x++) {
                all.add(result[x]);
            }
            if (all.size() > 0) {
                super.print(response, Boolean.valueOf(this.kjjggs_newsService.delete(all)));
            } else {
                // 删除数据不成功返回false
                super.print(response, "false");
            }
        } catch (Exception e) {
            e.printStackTrace();
            super.print(response, "false");
        }
    }

    @RequestMapping(value = "kggjjs_news_update")
    public void update( kjjggs_news vo, HttpServletResponse response) throws IOException {
        //保存数据库的路径
        String sqlPath = null;
        //定义文件保存的本地路径
        String Image_Path = config.Image_path_images;
        String localPath = Image_Path;
        //定义 文件名
        String filename = null;
        if (vo.getFile() != null) {
            //生成uuid作为文件名称
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            //获得文件类型（可以判断如果不是图片，禁止上传）
            String contentType = vo.getFile().getContentType();
            //获得文件后缀名
            String suffixName = contentType.substring(contentType.indexOf("/") + 1);
            //得到 文件名
            filename = uuid + "." + suffixName;
            //文件保存路径
            vo.getFile().transferTo(new File(localPath + File.separator + filename));
        }

        //把图片的相对路径保存至数据库
        sqlPath = filename;
        vo.setImage(sqlPath);
        try {
            if (this.kjjggs_newsService.update(vo)) {
                super.print(response, "success");
            } else {
                super.print(response, "false");
            }
        } catch (Exception e) {
            e.printStackTrace();
            super.print(response, "false");
        }
    }

    @Override
    public String getText() {
        return null;
    }

}